/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package my.SimulatorGUI1;

/**
 *
 * @author jda99448
 */
public class Timer implements Runnable {
    private Handler callBack;        //the object that handles the message
    private int repeats;            //how many times the Timer sends the message
    private long delay;             //interval between messages
    private String message;         //the message sent
    private boolean gag;            //toggles sending of message every interval
    private Thread runner;
    
    public Timer(String message, int delaySec, int repeats, Handler callBack){
        this.message = message;
        this.delay = delaySec * 1000; // convert millis to seconds
        this.repeats = repeats;
        this.callBack = callBack;
        gag = false;
        runner = new Thread(this);
        
        runner.start();
    }
    
    public void init(String message, int delaySec, int repeats, Handler callBack){
        this.message = message;
        this.delay = delaySec * 1000;
        this.repeats = repeats;
        this.callBack = callBack;
        gag = false;
    }
    
    public void gag(){
        gag = true;
    }
    public void ungag(){
        gag = false;
    }
    
    public void run(){
        while(repeats > 0){
                try {
                  System.err.println("Sleeping "+delay+" millis");
                  Thread.sleep(delay);
                }
                catch(InterruptedException e){
                    System.err.println("Thread Interrupted!");
                }
            if (!gag){
                System.err.println ("\""+message+"\" #"+repeats);
                callBack.handle(message);
            }
            --repeats;
        }
    }
    
}    
